home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13104 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  46 lines

  1. Path: li.net!jeremy
  2. From: jeremy@newshost.li.net (Jeremy Markman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Recursion
  5. Date: 4 Apr 1996 17:27:28 GMT
  6. Organization: LI Net (Long Island Network)
  7. Message-ID: <4k10q0$m5d@linet06.li.net>
  8. References: <31624BC2.70D2@sooner.net> <828548265snz@genesis.demon.co.uk>
  9. NNTP-Posting-Host: linet04.li.net
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Lawrence Kirby (fred@genesis.demon.co.uk) wrote:
  13.  
  14. : I think you've picked a bad example. You really need an extra argument in
  15. : this case to pass on a running accumulator. A more suitable problem would
  16. : be to write a recursive function that is passed an integer (unsigned is
  17. : easiest) and writes the character representation to stdout.
  18. Absolutely WRONG.  The whole point of recursion is that you do not need a 
  19. running accumulator.  When written correctly, the return value of each 
  20. recursive loop will be the correct accumulated value.  ANyhow, here is a 
  21. better version of what I already posted...
  22.  
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <math.h>
  27.  
  28. int convert(char *string)
  29.  {
  30.   int value;
  31.   int len = strlen(string);
  32.  
  33.   if (string[0] == '\0')
  34.     return(0);
  35.   value = convert(string+1);
  36.   value += ((string[0] - '0') * pow(10,len-1));
  37.   return(value);
  38.  }
  39.  
  40. void main()
  41.  {
  42.   char *string = "1234";
  43.  
  44.   printf("%d\n",convert(string));
  45.  }
  46.